package homework3.com.qianfeng.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanFactory {
	
	public static UserService createUserService() {
		UserService userService = new UserServiceImpl();
		TransactionManager transactionManager = new TransactionManager();
		UserService userServiceProxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), UserServiceImpl.class.getInterfaces(), new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Object returnVal = null;
				try {
					transactionManager.beginTransaction();
					returnVal = method.invoke(userService, args);
					transactionManager.commit();
				} catch (Exception e) {
					transactionManager.rollback();
				} finally {
					transactionManager.release();
				}
				return returnVal;
			}
		});
		return userServiceProxy;
	}
	
}
